package com.lebang.component;


import com.lebang.common.push.PushClient;
import com.lebang.entity.sys.LbbUser;
import com.lebang.example.LbbUserExample;
import com.lebang.mapper.LbbUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;


/**
 * @author Eliohn on 2019/8/27.
 * @version 1.0
 * 友盟推送的组件
 */
@Component
public class UMengPushComponent {
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private LbbUserMapper userMapper;

    // 友盟的推送
    @Autowired
    private  PushClient UMENG_PUSH_CLIENT ;

    /**
     * 发送通知
     *
     * @param title    标题
     * @param desc     内容
     * @param memberId 用户id
     *                 多个用,隔开
     *                 例如 "sadasd,21312,dasdas"
     * @return
     * @throws IOException
     */
    public void sendAndroidCustomizedcast(String title, String desc, String memberId) {
        UMENG_PUSH_CLIENT.sendByPushModel(title, desc, memberId);
    }

    /**
     * 发送通知但是不在APP读出来
     *
     * @param title    标题
     * @param desc     内容
     * @param memberId 用户id
     *                 多个用,隔开
     *                 例如 "sadasd,21312,dasdas"
     * @return
     * @throws IOException
     */
    public void sendNoRead(String title, String desc, String memberId) {
        UMENG_PUSH_CLIENT.sendByPushModel(title, desc, memberId);
    }



    /**
     * 推送给手机后台用的推送
     *
     * @param title
     * @param msg
     * @throws IOException
     */
    @Async
    public void sendTask(String title, String msg) throws IOException {
        String str = redisClient.get("XYHTSH_USER_LIST");
        String user = "";
        if (str == null) {
            LbbUserExample example = new LbbUserExample();
            List<LbbUser> users = userMapper.selectByExample(example);

            for (Iterator<LbbUser> iterator = users.iterator(); iterator.hasNext(); ) {
                LbbUser next = iterator.next();
                user = user + next.getUsername() + ",";
            }
            user = user.substring(0, user.length() - 1);
            redisClient.setex("XYHTSH_USER_LIST", user, 86400);
        } else {
            user = str;
        }
        UMENG_PUSH_CLIENT.sendTask(title, msg, user);
    }
}
